// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-11-20

package trace

import (
	"bytes"
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"html/template"
	"viewer/app"
	"viewer/app/search/elastic"
	"viewer/app/search/searched"
)

// Logic
// 查询链路日志.
type Logic struct {
	app.Assets

	request *Request
}

func New() logics.Logical {
	return &Logic{
		request: &Request{},
	}
}

func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	err = validator.Query(i, o.request)
	return
}

func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		buf []byte
		err error
		res = result.New()
		sch = elastic.New()
		tra *searched.Trace
	)

	// 1. 查询过程.
	if err = sch.Search(ctx, o.request.TraceId, o.request.SpanId, o.request.ParentSpanId); err != nil {
		res.WithError(err)
		return res
	}

	// 2. 结果排序.
	tra = sch.Mapper().Trace().Sort().Update()
	tra.TraceId = o.request.TraceId
	tra.SpanId = o.request.SpanId
	tra.ParentSpanId = o.request.ParentSpanId
	tra.CSS = o.GetTemplateForStyle()

	if buf, err = o.render(tra); err != nil {
		res.WithError(err)
		return res
	}

	// 3. 输出结果.
	res.WithHtml(buf)
	return res
}

func (o *Logic) render(data *searched.Trace) ([]byte, error) {
	var (
		buf  = make([]byte, 0)
		body = bytes.NewBuffer(buf)

		tpl = template.Must(template.New("body").Funcs(template.FuncMap{
			"span": o.renderSpan,
		}).Parse(o.GetTemplateForBody()))
	)

	err := tpl.Execute(body, data)
	return body.Bytes(), err
}

func (o *Logic) renderSpan(span *searched.Span) template.HTML {
	var (
		buf  []byte
		body = bytes.NewBuffer(buf)
		tmpl = template.Must(template.New("span").Funcs(template.FuncMap{
			"span": o.renderSpan,
		}).Parse(o.GetTemplateForSpan()))
	)

	if err := tmpl.Execute(body, span); err != nil {
		return template.HTML(err.Error())
	}
	return template.HTML(body.String())
}
